package dao

import (
	"team-evaluate/internal/model"
	"team-evaluate/pkg/app"
	"time"
)

func (d *Dao) CountTeam() (int64, error) {
	var count int64
	if err := d.engine.Model(&model.Team{}).Where("is_del = ?", 0).Count(&count).Error; err != nil {
		return 0, err
	}
	return count, nil
}

func (d *Dao) MyCountTeam(createdBy uint32) (int64, error) {
	var count int64
	if err := d.engine.Model(&model.Team{}).Where("is_del = ? AND created_by = ?", 0, createdBy).Count(&count).Error; err != nil {
		return 0, err
	}
	return count, nil
}

func (d *Dao) GetTeamList(createdBy uint32, page, pageSize int) ([]*model.TeamRes, error) {
	pageOffset := app.GetPageOffset(page, pageSize)
	var teams []*model.TeamRes
	var err error
	if pageOffset >= 0 && pageSize > 0 {
		d.engine = d.engine.Offset(pageOffset).Limit(pageSize)
	}
	if err = d.engine.Raw(
		`SELECT team.*, COUNT(ut.id) as user_count 
			FROM team 
			LEFT JOIN (SELECT * FROM user_team WHERE user_team.is_del = false) as ut 
			ON team.id = ut.team_id 
			WHERE team.is_del = false AND team.created_by = ? 
			GROUP BY team.id`, createdBy).
		Scan(&teams).Error; err != nil {
		return nil, err
	}
	return teams, nil
}

func (d *Dao) FindTeamById(id uint32) (*model.TeamRes, error) {
	team := model.TeamRes{}
	err := d.engine.Raw(
		`SELECT team.*, COUNT(ut.id) as user_count 
			FROM team 
			LEFT JOIN (SELECT * FROM user_team WHERE user_team.is_del = false) as ut 
			ON team.id = ut.team_id 
			WHERE team.is_del = false AND team.id = ?`, id).
		Scan(&team).Error
	if err != nil {
		return nil, err
	}
	return &team, nil
}

func (d *Dao) FindTeamByName(createdBy uint32, name string) ([]*model.TeamRes, error) {
	var teams []*model.TeamRes
	if err := d.engine.Raw(
		`SELECT team.*, COUNT(ut.id) as user_count 
			FROM team 
			LEFT JOIN (SELECT * FROM user_team WHERE user_team.is_del = false) as ut 
			ON team.id = ut.team_id 
			WHERE team.is_del = false AND team.created_by = ? AND team.name = ?
			GROUP BY team.id`, createdBy, name).
		Scan(&teams).Error; err != nil {
		return nil, err
	}
	return teams, nil
}

func (d *Dao) CreateTeam(name string, createdBy uint32, desc string) error {
	team := model.Team{
		Name:  name,
		Model: &model.Model{CreatedBy: createdBy},
		Desc:  desc,
	}
	return d.engine.Create(&team).Error
}

func (d *Dao) UpdateTeam(id uint32, name string, desc string) error {
	values := map[string]interface{}{}
	if name != "" {
		values["name"] = name
	}
	if desc != "" {
		values["desc"] = desc
	}
	return d.engine.Model(&model.Team{}).Where("id = ? AND is_del = ?", id, 0).Updates(values).Error
}

func (d *Dao) DeleteTeam(id uint32) error {
	nowTime := time.Now().Unix() * 1000
	return d.engine.Exec("update team set is_del = ?, deleted_on = ? where id = ?", true, nowTime, id).Error
}
